package com.example.springstudyvue.controller;


import com.example.springstudyvue.entity.Category;
import com.example.springstudyvue.mapper.CategoryMapper;
import com.example.springstudyvue.result.Result;
import com.example.springstudyvue.service.CategoryService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author linKe
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private CategoryMapper categoryMapper;





    @ApiOperationSupport(author = "linKe 的新增书籍接口")
    @ApiOperation(value="根据书籍信息新增",notes="返回操作结果")
    @PostMapping()
    public Result<Boolean> addCategory(@RequestBody Category category) {
        return Result.success(categoryService.addCategory(category));
    }

    @ApiOperation(value="根据书籍更新数据",notes="返回操作结果")
    @PutMapping()
    public Result<Boolean> updateCategory(@RequestBody Category category) {
        return Result.success(categoryService.updateCategory(category));
    }

    @ApiOperation(value="根据书籍ID删除",notes="返回操作结果")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCategory(@PathVariable("id") Long categoryId) {
        return Result.success(categoryService.deleteCategory(categoryId));
    }

    /**
     * 分类父子查询
     *
     * @return  分类查询
     */
    @GetMapping
    public Result<?> getAll() {
        // 先查询所有的数据
        List<Category> allCategories = categoryMapper.selectList(null);
        return Result.data(loopQuery(null, allCategories));
    }

    /**
     * 递归查询子集
     *  先查询结果再进行调用
     * @param pid   父级id也就是上层ID
     * @param allCategories 分类子集
     * @return  所有结果
     */
    private List<Category> loopQuery(Integer pid, List<Category> allCategories) {
        List<Category> categoryList = new ArrayList<>();
        for (Category category : allCategories) {
            if (pid == null) {
                //pid不存在
                if (category.getPid() == null) {
                    //添加到一级节点中
                    categoryList.add(category);
                    //再将当前ID作为父级ID去找下级子分类对象
                    category.setChildren(loopQuery(category.getId(), allCategories));
                }
                //pid存在
            } else if (pid.equals(category.getPid())) {
                //将数据添加进父级分类的集合中
                categoryList.add(category);
                //再向下递归 直到没有pid对应的数据时终止
                category.setChildren(loopQuery(category.getId(), allCategories));
            }
        }
        return categoryList;
    }







}
